05. Polymorphism
Polymorphism
ND079 C1 L3 A08 Polymorphism
Polymorphism is the ability of an object to take on many forms.
In Java, any kind of inheritance can be used to support polymorphism. In our vehicle example, each of the vehicles has two forms—for instance, a Car
object is both a Car
and also a Vehicle
(since it inherits from the Vehicle
class). Any Car
object thus has two forms. This is polymorphism.
If we wanted to get the speed of all the Car
, Boat
, and Plane
objects, we can easily do this because of polymorphism—we simply create a list containing all objects that are of type Vehicle
and get the speed on every Vehicle
object, regardless of whatever other types that object might be.
Here's what that would look like in code:
// Create an array of size 3 and type Vehicle
Vehicle [] vehicles = new Vehicle[3];
// Instantiate three new objects and add them to the array.
// It looks like these are all different types (Car, Plane, and Boat),
// but they all inherit from the Vehicle class, so in addition to the types
// they get from their subclasses, they are also all Vehicle objects.
vehicles[0] = new Car();
vehicles[1] = new Plane();
vehicles[2] = new Boat();
// Iterate over the array and print the speed
// of each of the Vehicle objects.
for (int i = 0; i < vehicles.length; i++) {
vehicles[i].speed();
}